package com.future.common.listener.nettysocketio;

import java.util.Date;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.DataListener;
import com.future.common.bean.Chat;
import com.future.common.utils.IDUtil;
import com.future.common.utils.SocketIoUtil;
import com.future.model.Records;
import com.future.model.SysUser;
import com.future.service.AuthenticationService;
import com.future.service.SysUserService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.CPI;
import com.jfinal.plugin.activerecord.tx.Tx;

import net.minidev.json.JSONObject;

public class ChatListener implements DataListener<Chat> {
	@Inject
	private AuthenticationService authenticationService;
	@Inject
	private SysUserService sysUserService;
	
	@Override
	@Before(Tx.class)
	public void onData(SocketIOClient client, Chat data, AckRequest ackSender) throws Exception {
		String token = client.getHandshakeData().getSingleUrlParam("Authorization");
		JSONObject result = this.authenticationService.parseToken(token);
		String userid = result.getAsString("userid");
		SysUser currentUser = this.sysUserService.findUserById(userid);
		String name = currentUser.getXm();
		Date now = new Date();
		Records records = new Records();
		records.setId(IDUtil.getId());
		records.setName(name);
		records.setMessage(data.getMessage());
		records.setSendtime(now);
		records.setUserid(userid);
		records.setMettingid(data.getMettingId());
		records.save();
		SocketIoUtil.sendBroadcastMessage(data.getMettingId(), JsonKit.toJson(CPI.getAttrs(records)));
	}

}
